package com.lujianfei.powersearch.ui.createOrUpdate.viewmodel

import android.view.View
import androidx.databinding.ObservableField
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lujianfei.powersearch.database.SearchItemModel
import com.lujianfei.powersearch.logger.LoggerFactory
import com.lujianfei.powersearch.ui.createOrUpdate.widget.imageviewedit.model.ImageViewEditItem
import com.lujianfei.powersearch.utils.Constant
import com.lujianfei.powersearch.utils.ImageUtils
import com.orm.SugarRecord
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Calendar
import java.util.Date
import java.util.Locale

class CreateOrUpdateViewModel: ViewModel() {

    val tag = "CreateOrUpdateViewModel"
    val log = LoggerFactory.getLogger()

    val info = ObservableField("")
    val keyword = ObservableField("")
    val location = ObservableField("")
    val cost = ObservableField("")
    val bindLink = ObservableField("")
    val packageName = ObservableField("")
    val bindAppName = ObservableField("")

    // 开始时间
    val startDateStr = ObservableField("")
    val startTimeStr = ObservableField("")
    var startDateTimeStamp = 0L
    var startTimeTimeStamp = 0L

    val onStartReset =  View.OnClickListener {
        startDateStr.set("")
        startTimeStr.set("")
        startDateTimeStamp = 0L
        startTimeTimeStamp = 0L
    }

    val startTimeStamp:Long
    get() = startDateTimeStamp + startTimeTimeStamp


    // 结束时间
    val endDateStr = ObservableField("")
    val endTimeStr = ObservableField("")
    var endDateTimeStamp = 0L
    var endTimeTimeStamp = 0L

    val onEndReset =  View.OnClickListener {
        endDateStr.set("")
        endTimeStr.set("")
        endDateTimeStamp = 0L
        endTimeTimeStamp = 0L
    }

    val endTimeStamp:Long
        get() = endDateTimeStamp + endTimeTimeStamp

    val showProgress = ObservableField(false)
    val showDeleteButton = ObservableField(false)
    var finishCallback:(()->Unit) ?= null

    var searchItemModel: SearchItemModel? = null
    var parentId = Constant.RootId.toLong()
    var parentName: String? = null

    var searchItemModels: MutableList<SearchItemModel?> = ArrayList()
    fun deleteCurrentAndSubItem(searchItemModel: SearchItemModel?) {
        showProgress.set(true)
        viewModelScope.launch {
            withContext(Dispatchers.IO) {
                searchItemModels.clear()
                searchItemModels.add(searchItemModel)
                recursive(searchItemModel)
                if (searchItemModels.isNotEmpty()) {
                    for (searchItem in searchItemModels) {
                        searchItem!!.delete()
                    }
                }
            }
            showProgress.set(false)
            finishCallback?.invoke()
        }
    }

    fun getImageList():List<ImageViewEditItem> {
        val result = arrayListOf<ImageViewEditItem>()
        if (searchItemModel?.imagePath?.isNotBlank() == true) {
            val imageArr = searchItemModel?.imagePath?.split(",")
            imageArr?.let { imageArr->
                if (imageArr.isNotEmpty()) {
                    imageArr.forEach {
                        result.add(ImageUtils.getImageByPath(it))
                    }
                } else {
                    searchItemModel?.imagePath?.let {
                        result.add(ImageUtils.getImageByPath(it))
                    }
                }
            }
        }
        result.add(ImageViewEditItem(imageUri = null, type = ImageViewEditItem.TYPE_ADD))
        return result
    }

    fun updateDataToView() {
        info.set(searchItemModel?.name)
        keyword.set(searchItemModel?.keywords)
        location.set(searchItemModel?.location)
        cost.set(searchItemModel?.cost)
        bindAppName.set(searchItemModel?.appName)
        packageName.set(searchItemModel?.packageName)
        updateStartTime(searchItemModel?.startTime)
        updateEndTime(searchItemModel?.endTime)
    }

    private fun recursive(root: SearchItemModel?) {
        val models = SugarRecord.find(SearchItemModel::class.java, "parentId=?", "" + root!!.id)
        if (null != models && models.isNotEmpty()) {
            for (d in models) {
                recursive(d)
            }
            searchItemModels.addAll(models)
        }
    }


    /**
     * 更新开始时间
     */
    fun updateStartTime(startTime: Long?) {
        updateTime(timeStamp = startTime) { dateStr:String, timeStr:String, dateTimeStamp:Long, timeTimeStamp:Long->
            startDateStr.set(dateStr)
            startTimeStr.set(timeStr)
            startDateTimeStamp = dateTimeStamp
            startTimeTimeStamp = timeTimeStamp
        }
    }

    /**
     * 更新结束时间
     */
    fun updateEndTime(endTime: Long?) {
        updateTime(timeStamp = endTime) { dateStr:String, timeStr:String, dateTimeStamp:Long, timeTimeStamp:Long->
            endDateStr.set(dateStr)
            endTimeStr.set(timeStr)
            endDateTimeStamp = dateTimeStamp
            endTimeTimeStamp = timeTimeStamp
        }
    }

    private fun updateTime(timeStamp: Long?, callback:(dateStr:String, timeStr:String, dateTimeStamp:Long, timeTimeStamp:Long)->Unit) {
        timeStamp?.let {
            if (it == 0L) {
                return@let
            }
            val calendar = Calendar.getInstance()
            calendar.time  = Date(it * 1000)
            val dateStr = SimpleDateFormat("yyyy-MM-dd", Locale.CHINA).format(calendar.time)
            val timeStr = SimpleDateFormat("HH:mm", Locale.CHINA).format(calendar.time)

            // 获取日期
            val year = calendar.get(Calendar.YEAR)
            val month = calendar.get(Calendar.MONTH)
            val dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH)
            val hourOfDay = calendar.get(Calendar.HOUR_OF_DAY)
            val minute = calendar.get(Calendar.MINUTE)

            val timeStrTmp = String.format("%04d-%02d-%02d", year, month + 1, dayOfMonth)
            val l = LocalDate.parse(timeStrTmp, DateTimeFormatter.ofPattern("yyyy-MM-dd"))
            val dateTimeStamp = l.atStartOfDay(ZoneId.systemDefault()).toInstant().epochSecond

            // 获取时间
            val timeTimeStamp = (hourOfDay * 60 * 60 + minute * 60).toLong()

            callback.invoke(dateStr, timeStr, dateTimeStamp, timeTimeStamp)
        }
    }

    fun removeImagePath(imageUrl: String?) {
        imageUrl?.let {
            val file = File(imageUrl)
            val result = file.delete()
            log.d(tag, "removeImagePath file $imageUrl, delete result:$result")
        }
    }
}